package cn.fl.ass.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.ass.service.IAssTrailCarDInfService;
import cn.fl.ass.service.IAssTrailCarDService;
import cn.fl.ass.service.IAssTrailCarMService;
import cn.fl.ass.vo.AssTrailCarDInfVO;
import cn.fl.ass.vo.AssTrailCarDVO;
import cn.fl.ass.vo.AssTrailCarMVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.constant.SysLogConstant;

import com.alibaba.fastjson.JSONObject;

import fl.ass.facade.condition.AssTrailCarDInfQueryCondition;

/**
 * @Description: 拖车实际信息明细表 控制层
 */
@Controller
@RequestMapping("/ass/assTrailCarDInf")
public class AssTrailCarDInfController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(AssTrailCarDInfController.class);

	/**
	 * AssTrailCarDInf 服务层BEAN
	 */
	@Autowired
	private IAssTrailCarDInfService assTrailCarDInfService;
	
	/**
	 * AssTrailCarM 服务层BEAN
	 */
	@Autowired
	private IAssTrailCarMService assTrailCarMService;
	
	/**
	 * AssTrailCarD 服务层BEAN
	 */
	@Autowired
	private IAssTrailCarDService assTrailCarDService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("ass/assTrailCarDInf/list");
		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("ass/assTrailCarDInf/modify");
		view.addObject("id", id);
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String searchName = request.getParameter("demo.name");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		AssTrailCarDInfQueryCondition qc = new AssTrailCarDInfQueryCondition();
		if (StringUtils.isNotEmpty(searchName)) {
			//TODO SOMTHING
		}
		page.setCondition(qc);

		//TODO SOMETHING
		Pager pager = new Pager();//this.assTrailCarDInfService.searchListPage(page);
		List<AssTrailCarDInfVO> list = (List<AssTrailCarDInfVO>) pager.getResultList();
		ListPageVO<AssTrailCarDInfVO> listPage = new ListPageVO<AssTrailCarDInfVO>(list, pager.getTotalCount());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.assTrailCarDInfService.removeById(Long.valueOf(id));
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 拖车实际明细信息
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("tcInfoId");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		
		try {
			AssTrailCarDInfVO vo = this.assTrailCarDInfService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
			}
			result.setData(vo);
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.newLogger("获取拖车实际明细信息失败 BaseException").setThrowable(ex).setKeys("id:" + id).info();
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.newLogger("获取拖车实际明细信息失败 Exception").setThrowable(ex).setKeys("id:" + id).info();
		}
		return result;
	}

	/**
	 * 新增拖车实际信息明细表信息
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		//获取页面参数
		String tcMasterId = request.getParameter("tcMasterId");
		String tcDetailId = request.getParameter("tcDetailId");
		String actPayDt = request.getParameter("actPayDt");
		String actPayAmt = request.getParameter("actPayAmt");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		AssTrailCarDInfVO entity = null;
		try {
			entity = new AssTrailCarDInfVO();
			if(StringUtils.isNotEmpty(tcMasterId)){
				entity.setMasterId(Long.valueOf(tcMasterId));
			}else{
			    result.setSuccess(BaseConstant.IS_YESNO_NO);
			    result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			    return result;
			}
			if(StringUtils.isNotEmpty(tcDetailId)){
				entity.setDetailId(Long.valueOf(tcDetailId));
				//保存实际拖车费用
				if(StringUtils.isNotEmpty(actPayAmt)){//元转分
					AssTrailCarDVO entity2 = new AssTrailCarDVO();
					entity2.setId(Long.valueOf(tcDetailId));
					entity2.setActBackAmt(DecimalUtils.convertYuanToFen(Double.valueOf(actPayAmt)));
					//设置主表实体属性
					entity2.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
					entity2.setMdfTm(new Date());
					boolean success = this.assTrailCarDService.modify(entity2);
					if(!success){
						result.setSuccess(BaseConstant.IS_YESNO_NO);
						result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
						BaseLogUtils.newLogger("修改实际拖车费用失败").setKeys("id:" + tcDetailId, "DATA:" + JSONObject.toJSONString(entity2)).info();
					}
				}
			}else{
                BaseLogUtils.newLogger("新增拖车实际信息明细表数据 tcDetailId 为空").info();
			}
			if(StringUtils.isNotEmpty(actPayDt)){
				entity.setActPayDt(DateUtils.formatStringToDate(actPayDt, DateUtils.YYYY_MM_DD));
			}
			if(StringUtils.isNotEmpty(actPayAmt)){//元转分
				entity.setActPayAmt(DecimalUtils.convertYuanToFen(Double.valueOf(actPayAmt)));
			}
			entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			Long id = this.assTrailCarDInfService.add(entity);
			if(id != null){
				AssTrailCarDVO entity2 = new AssTrailCarDVO();
				entity2.setId(Long.valueOf(tcDetailId));
				//设置扩展表ID(拖车实际明细表)
				if(StringUtils.isNotEmpty(id)){
					entity2.setInfoId(id);;
					boolean success = this.assTrailCarDService.modify(entity2);
					if(!success){
					    BaseLogUtils.newLogger("更新拖车信息表扩展表ID失败").setKeys("id:" + id, "DATA:" + JSONObject.toJSONString(entity2)).info();
					}
				}else{
                    BaseLogUtils.newLogger("无法更新拖车信息表数据 id为空").setKeys("DATA:" + JSONObject.toJSONString(entity)).info();
				}
			}
			result.setData(id);
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.newLogger("新增拖车实际信息明细表数据失败 BaseException").setThrowable(ex).setKeys("DATA:" + JSONObject.toJSONString(entity)).info();
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.newLogger("新增拖车实际信息明细表数据失败 Exception").setThrowable(ex).setKeys("DATA:" + JSONObject.toJSONString(entity)).info();
		}

		return result;
	}

	/**
	 * 修改拖车实际明细表
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		//拖车实际明细表
		String tcInfoId = request.getParameter("tcInfoId");
		String futureAmt = request.getParameter("futureAmt");
		String overRentAmt = request.getParameter("overRentAmt");//逾期租金
		String overInterestAmt = request.getParameter("overInterestAmt");//逾期罚息
		String performanceAmt = request.getParameter("performanceAmt");
		String insureAmt = request.getParameter("insureAmt");
		String riskAmt = request.getParameter("riskAmt");
		String otherAmt = request.getParameter("otherAmt");
		String baseAmt = request.getParameter("baseAmt");
		//拖车主表-付款信息
		String tcMasterId = request.getParameter("tcMasterId");
		String tcDetailId = request.getParameter("tcDetailId");
		String payerAccNm = request.getParameter("payerAccNm");
		String payerAccNo = request.getParameter("payerAccNo");
		String payerBankNm = request.getParameter("payerBankNm");
		String actPayDt = request.getParameter("actPayDt");
		String actPayAmt = request.getParameter("actPayAmt");
		String flag = request.getParameter("flag");//流程标识
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(tcInfoId)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		if(StringUtils.isEmpty(tcMasterId)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		AssTrailCarDInfVO entity1 = new AssTrailCarDInfVO();
		AssTrailCarMVO entity2 = new AssTrailCarMVO();
		try {
			//设置拖车实际明细表实体
			entity1.setId(Long.valueOf(tcInfoId));
			entity1.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
			//判断是发起人,还是标记拖车状态的人
			if(StringUtils.isNotEmpty(flag)){
				if("21".equals(flag) || "22".equals(flag)){//修改拖车实际明细信息
					if(StringUtils.isNotEmpty(futureAmt)){//元转分
						entity1.setFutureAmt(DecimalUtils.convertYuanToFen(Double.valueOf(futureAmt)));
					}
					if(StringUtils.isNotEmpty(overRentAmt)){//元转分-逾期租金
						entity1.setOverRentAmt(DecimalUtils.convertYuanToFen(Double.valueOf(overRentAmt)));
					}
					if(StringUtils.isNotEmpty(overInterestAmt)){//元转分-逾期罚息
						entity1.setOverInterestAmt(DecimalUtils.convertYuanToFen(Double.valueOf(overInterestAmt)));
					}
					if(StringUtils.isNotEmpty(performanceAmt)){//元转分
						entity1.setPerformanceAmt(DecimalUtils.convertYuanToFen(Double.valueOf(performanceAmt)));
					}
					if(StringUtils.isNotEmpty(insureAmt)){//元转分
						entity1.setInsureAmt(DecimalUtils.convertYuanToFen(Double.valueOf(insureAmt)));
					}
					if(StringUtils.isNotEmpty(riskAmt)){//元转分
						entity1.setRiskAmt(DecimalUtils.convertYuanToFen(Double.valueOf(riskAmt)));
					}
					if(StringUtils.isNotEmpty(otherAmt)){//元转分
						entity1.setOtherAmt(DecimalUtils.convertYuanToFen(Double.valueOf(otherAmt)));
					}
					if(StringUtils.isNotEmpty(baseAmt)){//元转分
						entity1.setBaseAmt(DecimalUtils.convertYuanToFen(Double.valueOf(baseAmt)));
					}
					boolean success1 = this.assTrailCarDInfService.modify(entity1);
					//设置拖车主表实体
					entity2.setId(Long.parseLong(tcMasterId));
					entity2.setPayerAccNm(payerAccNm);
					entity2.setPayerAccNo(payerAccNo);
					entity2.setPayerBankNm(payerBankNm);
					entity2.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
					boolean success2 = this.assTrailCarMService.modify(entity2);
					if(!success1 || !success2){
						result.setSuccess(BaseConstant.IS_YESNO_NO);
						result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
					}
				}else if("9".equals(flag) || "17".equals(flag)){//修改实际付款信息
					if(StringUtils.isNotEmpty(actPayDt)){
						entity1.setActPayDt(DateUtils.formatStringToDate(actPayDt, DateUtils.YYYY_MM_DD));
					}
					if(StringUtils.isNotEmpty(actPayAmt)){//元转分
						entity1.setActPayAmt(DecimalUtils.convertYuanToFen(Double.valueOf(actPayAmt)));
					}
					boolean success3 = this.assTrailCarDInfService.modify(entity1);
					if(!success3){
						result.setSuccess(BaseConstant.IS_YESNO_NO);
						result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
					}
					if(StringUtils.isNotEmpty(tcDetailId)){
						//保存实际拖车费用
						AssTrailCarDVO entity3 = new AssTrailCarDVO();
						entity3.setId(Long.valueOf(tcDetailId));
						if(StringUtils.isNotEmpty(actPayAmt)){//元转分
							entity3.setActBackAmt(DecimalUtils.convertYuanToFen(Double.valueOf(actPayAmt)));
							//设置主表实体属性
							entity3.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
							entity3.setMdfTm(new Date());
							boolean success = this.assTrailCarDService.modify(entity3);
							if(!success){
								result.setSuccess(BaseConstant.IS_YESNO_NO);
								result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
							}
						}
					}
				}
			}
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.newLogger("修改拖车实际明细数据失败 BaseException").setThrowable(ex).setKeys("id:" + tcInfoId, "DATA:" + JSONObject.toJSONString(entity1)).info();
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.newLogger("修改拖车实际明细数据失败 Exception").setThrowable(ex).setKeys("id:" + tcInfoId, "DATA:" + JSONObject.toJSONString(entity1)).info();
		}
		return result;
	}
	
	/**
	 * 根据支付表ID查询财务核算保底价金额信息
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getMoneyByPaySchId.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getMoneyByPaySchId(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String paySchId = request.getParameter("paySchId");
		List<Long> ids = new ArrayList<Long>();
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(paySchId)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}else{
			ids.add(Long.valueOf(paySchId));
		}
		
		try {
			List<AssTrailCarDInfVO> vo = this.assTrailCarDInfService.selectMoneyByPaySchId(ids);
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
			}else{
				if(vo.size()>0){
					result.setData(vo.get(0));
				}else{
					result.setData(vo);
				}
			}
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.newLogger("根据支付表ID查询财务核算保底价金额信息失败 BaseException").setThrowable(ex).setKeys("paySchId:" + paySchId).info();
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.newLogger("根据支付表ID查询财务核算保底价金额信息失败 Exception").setThrowable(ex).setKeys("paySchId:" + paySchId).info();
		}
		return result;
	}
	
	@RequestMapping(value = "/modifyMarketInfo.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modifyMarketInfo(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,SysLogConstant.LOG_CMM_OPERATE_SUCC);
		String tcInfoId = request.getParameter("tcInfoId");
		String marketAmt = request.getParameter("marketAmt");
		String marketDt = request.getParameter("marketDt");
		if(StringUtils.isEmpty(tcInfoId)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "拖车明细ID不能为空.");
		}
		if(StringUtils.isEmpty(marketAmt)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "市场评估价不能为空.");
		}
		if(StringUtils.isEmpty(marketDt)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "市场评估时间不能为空.");
		}
		AssTrailCarDInfVO entity = new AssTrailCarDInfVO();
		try {
			entity.setId(Long.valueOf(tcInfoId));
			entity.setMarketAmt(DecimalUtils.convertYuanToFen(Double.valueOf(marketAmt)));
			entity.setMarketDt(DateUtils.formatStringToDate(marketDt, DateUtils.YYYY_MM_DD));
			boolean success = this.assTrailCarDInfService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_OPERATE_FAIL);
				return result;
			}
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.newLogger("修改拖车明细信息失败 BaseException").setThrowable(ex).setKeys("DATA:"+JSONObject.toJSONString(entity)).info();
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
            BaseLogUtils.newLogger("修改拖车明细信息失败 Exception").setThrowable(ex).setKeys("DATA:"+JSONObject.toJSONString(entity)).info();
		}
		return result;
	}
}

